package com.example.tang.zhayan.ui;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.tang.zhayan.BaseApp;
import com.example.tang.zhayan.R;
import com.example.tang.zhayan.adapter.SplashImgAdapter;
import com.example.tang.zhayan.bean.BaseDesignerDetail;
import com.example.tang.zhayan.bean.BaseDesignerDetailAttribute;
import com.example.tang.zhayan.bean.BaseDesignerDetailBuy;
import com.example.tang.zhayan.bean.BaseDesignerDetailBuyColor;
import com.example.tang.zhayan.bean.DbBuyDetail;
import com.example.tang.zhayan.bean.DesignerDetailBuyColor;
import com.example.tang.zhayan.bean.DesignerDetailBuyItem;
import com.example.tang.zhayan.bean.DesignerDetailItem;
import com.example.tang.zhayan.constant.PathConstant;
import com.example.tang.zhayan.db.FileUtils;
import com.example.tang.zhayan.utils.EventUtils;
import com.example.tang.zhayan.utils.IntentUtils;
import com.example.tang.zhayan.utils.ResultParamsUtils;
import com.example.tang.zhayan.utils.WindowsUtils;
import com.squareup.picasso.Picasso;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;
import org.xutils.common.Callback;
import org.xutils.common.util.LogUtil;
import org.xutils.ex.DbException;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.sharesdk.onekeyshare.OnekeyShare;


/**
 * Created by tang on 2015/12/16.
 */

/**
 * Created by tang on 2015/12/16.
 */
@ContentView(R.layout.activity_buy)
public class BuyDetailsActivity extends AppCompatActivity implements View.OnClickListener, RadioGroup.OnCheckedChangeListener {
    //UI
    @ViewInject(R.id.viewpager_buy)
    private ViewPager viewPagerBuy;
    @ViewInject(R.id.tv_buy_old)
    private TextView oldPrice;
    @ViewInject(R.id.tv_buy_new)
    private TextView newPrice;
    @ViewInject(R.id.tv_buy_num)
    private TextView txtNum;
    @ViewInject(R.id.iv_buy_attribute)
    private ImageView ivAttribute;
    @ViewInject(R.id.iv_buy_ask)
    private ImageView ivAsk;
    @ViewInject(R.id.iv_buy_know)
    private ImageView ivKnow;
    @ViewInject(R.id.img_works_search)
    private ImageView ivSearch;
    @ViewInject(R.id.img_buy_bag)
    private ImageView ivBag;
    @ViewInject(R.id.tv_buy)
    private TextView tv_buy;
    @ViewInject(R.id.tv_buy_topnum)
    private TextView textNum;
    //数据
    private SplashImgAdapter adapter;
    private List<ImageView> imageViewList;
    private Map<String, String> map;
    private String id;
    private String memberId;
    private List<DesignerDetailBuyItem> lisItem;
    private List<String> lisImgUrl;
    private PopupWindow popupWindow;
    private DesignerDetailItem data;
    private ProgressDialog dialog;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
        EventBus.getDefault().register(this);
        //每次进来的时候查询数据库是否有商品
        EventUtils.setGoodsNum(textNum);

        dialog = new ProgressDialog(this);
        dialog.setMessage("数据正咋加载中");
        dialog.show();


        popupWindow = new PopupWindow();
        //设置购买的监听
        tv_buy.setOnClickListener(this);
        initList();
        getId();
        adapter = new SplashImgAdapter(imageViewList);
        viewPagerBuy.setAdapter(adapter);
        getData();
        ivBag.setOnClickListener(this);
    }


    /**
     * 添加Popupwindow
     */
    private void addPopupWindow(String str1, String str2, View v) {
        View view = getLayoutInflater().inflate(R.layout.buy_popupwindow_view, null);
        TextView textName = (TextView) view.findViewById(R.id.buy_details_name);
        TextView textContext = (TextView) view.findViewById(R.id.buy_details_context);
        TextView textHide = (TextView) view.findViewById(R.id.popup_window_hide);
        textContext.setText(str2);
        textName.setText(str1);
        final AbsListView.LayoutParams params = new AbsListView.LayoutParams(new WindowsUtils(this)
                .getScreenWidth(), new WindowsUtils(this).getScreenHeight());
        view.setLayoutParams(params);
        popupWindow = new PopupWindow(view, new WindowsUtils(this)
                .getScreenWidth(), new WindowsUtils(this).getScreenHeight());
        popupWindow.setBackgroundDrawable(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
        popupWindow.setOutsideTouchable(true);

        //PopupWindow的隐藏点击事件
        textHide.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });

        popupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);
        //在底部显示Popupwindow
        popupWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);
    }


    /**
     * 分享
     */
    private void showShare(String str) {
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();
// 分享时Notification的图标和文字  2.5.9以后的版本不调用此方法
//        oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
//        oks.setTitle(getString(R.string.share));
        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
//        oks.setTitleUrl("http://sharesdk.cn");
        // text是分享文本，所有平台都需要这个字段
        oks.setText(str);
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
//        oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
        // url仅在微信（包括好友和朋友圈）中使用
//        oks.setUrl("http://sharesdk.cn");
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
//        oks.setComment("我是测试评论文本");
        // site是分享此内容的网站名称，仅在QQ空间使用
//        oks.setSite(getString(R.string.app_name));
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
//        oks.setSiteUrl("http://sharesdk.cn");
// 启动分享GUI
        oks.show(this);
    }


    /**
     * viewPager的滑动事件
     */
    private void addListener() {
        viewPagerBuy.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                txtNum.setText((position + 1) + "/" + (lisImgUrl.size()));
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }


    private void initList() {
        imageViewList = new ArrayList<>();
        lisImgUrl = new ArrayList<>();
        lisItem = new ArrayList<>();
        map = new HashMap<>();
    }


    /**
     * 给map加入值
     */
    private void initMap() {
        map.put("id", id);
        map.put("memberId", memberId);
    }

    /**
     * 获取数据源
     */
    public void getData() {
        x.http().post(ResultParamsUtils.getIDParams(PathConstant.WORKS_DETAILS, map), new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String s) {
                BaseDesignerDetail buy = JSON.parseObject(s, BaseDesignerDetail.class);
                //如果进度调试显示的就隐藏
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }
                data = buy.getData().getItem();
                if (data != null) {
                    initListImgUrl(data);
                    for (int i = 0; i < lisImgUrl.size(); i++) {
                        ImageView view = new ImageView(BuyDetailsActivity.this);
                        view.setScaleType(ImageView.ScaleType.FIT_XY);
                        x.image().bind(view, lisImgUrl.get(i));
                        imageViewList.add(view);
                    }
                    adapter.notifyDataSetChanged();
                    oldPrice.setText("￥" + data.getOld_prc() + ".00");
                    oldPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
                    newPrice.setText("￥" + data.getNew_prc() + ".00");
                    /**
                     * 编语点击事件
                     */
                    ivAsk.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            addPopupWindow(data.getItem_name(), data.getStory(), v);
                        }
                    });
                    /**
                     * 须知点击事件
                     */
                    ivKnow.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            addPopupWindow(data.getItem_name(), data.getNeed_to_know(), v);
                        }
                    });
                    /**
                     * 分享商品的数据
                     */
                    ivSearch.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            showShare(data.getItem_name() + "" + data.getStory() + "" + data.getNeed_to_know());
                        }
                    });
                    /**
                     * 属性点击事件
                     */
                    ivAttribute.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(final View v) {
                            map.clear();
                            map.put("id", id);
                            x.http().post(ResultParamsUtils.getIDParams(PathConstant.WORKS_ATTRIBUTE, map), new CommonCallback<String>() {
                                @Override
                                public void onSuccess(String s) {
                                    BaseDesignerDetailAttribute item = JSON.parseObject(s, BaseDesignerDetailAttribute.class);
                                    String str = item.getData().getList().get(0).getDetail() + "\n"
                                            + item.getData().getList().get(0).getProperty() + "\n"
                                            + item.getData().getList().get(1).getDetail() + "\n"
                                            + item.getData().getList().get(1).getProperty() + "\n";
                                    addPopupWindow(str, "", v);
                                }

                                @Override
                                public void onError(Throwable throwable, boolean b) {
                                }

                                @Override
                                public void onCancelled(CancelledException e) {
                                }

                                @Override
                                public void onFinished() {
                                }
                            });
                        }
                    });
                    addListener();
                }
            }

            @Override
            public void onError(Throwable throwable, boolean b) {
            }

            @Override
            public void onCancelled(CancelledException e) {

            }

            @Override
            public void onFinished() {

            }
        });

    }

    /**
     * 得到图片的地址
     */
    private void initListImgUrl(DesignerDetailItem item) {
        getUrl(item.getImg1());
        getUrl(item.getImg2());
        getUrl(item.getImg3());
        getUrl(item.getImg4());
        getUrl(item.getImg5());
    }

    /**
     * 判断图片地址是否为空
     *
     * @param str
     */
    public void getUrl(String str) {
        if (!str.equals("")) {
            lisImgUrl.add(str);
        }

    }

    /**
     * 获取传过来的id值
     */
    public void getId() {
        Intent intent = getIntent();
        id = intent.getStringExtra("id");
        memberId = intent.getStringExtra("memberId");
        initMap();
    }

    //点击购买后的界面   衣服尺寸和颜色的集合
    private List<DesignerDetailBuyColor> corolList = new ArrayList<>();
    private List<DesignerDetailBuyItem> sizeList = new ArrayList<>();


    /**
     * 判断是否填写身高体重  颜色  尺寸
     *
     * @return
     */
    private boolean isCompleteInfo() {
        boolean isCompleteInfo = false;
        String height = et_height.getText().toString();
        String kg = et_kg.getText().toString();
        if (isCheckedSize && isCheckedColor && !height.equals("") && !kg.equals("")) {
            isCompleteInfo = true;
        }
        return isCompleteInfo;
    }

    /**
     * 设置数据库的对象
     */
    private void setDbInfo() {
        dbBuyDetail.setCurrentCount(currentCount + "");
        dbBuyDetail.setTotalCount(totalCount + "");
        dbBuyDetail.setName(data.getItem_name());
        dbBuyDetail.setImgUrl(data.getCover());
        dbBuyDetail.setInfo(data.getStudioName());
        dbBuyDetail.setPrice("￥" + data.getNew_prc());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_buy:
                getBuyColor();
                getBuySize();
                showBuyPop();
                break;
            case R.id.view_top:
            case R.id.iv_pop_dismiss:
                popupWindow.dismiss();
                break;
            case R.id.img_buy_bag:
                IntentUtils.toShopBag(this);
                break;
            case R.id.tv_buy_db://直接购买
                if (isCompleteInfo()) {
                    Intent intent = new Intent(this, OrderActivity.class);
                    setDbInfo();
                    intent.putExtra("dbInfo", dbBuyDetail);
                    startActivity(intent);
                    popupWindow.dismiss();
                } else {
                    Toast.makeText(this, "请选择喜欢的颜色尺寸和合适身高体重", Toast.LENGTH_SHORT).show();
                }

                break;
            case R.id.tv_addto_db://加入购物袋
                if (isCompleteInfo()) {
                    setDbInfo();
                    try {
                        BaseApp.getApp().getDb().save(dbBuyDetail);
                        Toast.makeText(this, "已加入购买袋", Toast.LENGTH_SHORT).show();
                        EventBus.getDefault().post("1", "buy");
                    } catch (DbException e) {
                        e.printStackTrace();
                    }
                    popupWindow.dismiss();
                } else {
                    Toast.makeText(this, "请选择喜欢的颜色尺寸和合适身高体重", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.iv_add:
                if (currentCount < totalCount) {
                    currentCount++;
                    tv_current_count.setText(currentCount + "");
                } else {
                    Toast.makeText(this, "已经是最大库存了", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.iv_delete:
                if (currentCount > 1) {
                    currentCount--;
                    tv_current_count.setText(currentCount + "");
                } else {
                    Toast.makeText(this, "大人多买点吧", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    /**
     * 加载购买界面的pop
     */

    private void showBuyPop() {
        View view = getLayoutInflater().inflate(R.layout.buy_detail_pop_layout, null);
        initBuyPopView(view);
    }

    RadioGroup rg_color;
    RadioGroup rg_size;


    private int totalCount;
    private int currentCount = 1;
    private TextView tv_current_count;
    private EditText et_height;
    private EditText et_kg;

    /**
     * 初始化购买界面的控件
     */
    private void initBuyPopView(View view) {
        ImageView iv_pop_dismiss = (ImageView) view.findViewById(R.id.iv_pop_dismiss);
        iv_pop_dismiss.setOnClickListener(this);
        ImageView iv_clothes = (ImageView) view.findViewById(R.id.iv_clothes);
        TextView tv_info = (TextView) view.findViewById(R.id.tv_info);
        TextView tv_name = (TextView) view.findViewById(R.id.tv_name);
        TextView tv_price = (TextView) view.findViewById(R.id.tv_price);
        tv_info.setText(data.getItem_name());
        tv_name.setText(data.getStudioName());
        tv_price.setText("￥" + data.getNew_prc());
        Picasso.with(this).load(data.getCover()).placeholder(R.mipmap.default_loader_image1).into(iv_clothes);

        rg_color = (RadioGroup) view.findViewById(R.id.rg_color);
        rg_size = (RadioGroup) view.findViewById(R.id.rg_size);
        rg_color.setOnCheckedChangeListener(this);
        rg_size.setOnCheckedChangeListener(this);

        TextView tv_buy_db = (TextView) view.findViewById(R.id.tv_buy_db);
        TextView tv_addto_db = (TextView) view.findViewById(R.id.tv_addto_db);
        tv_buy_db.setOnClickListener(this);
        tv_addto_db.setOnClickListener(this);

        ImageView iv_add = (ImageView) view.findViewById(R.id.iv_add);
        ImageView iv_delete = (ImageView) view.findViewById(R.id.iv_delete);
        iv_add.setOnClickListener(this);
        iv_delete.setOnClickListener(this);

        TextView tv_total_count = (TextView) view.findViewById(R.id.tv_total_count);
        tv_current_count = (TextView) view.findViewById(R.id.tv_buy_count);
        String item_quantity = data.getItem_quantity();
        tv_total_count.setText(item_quantity);
        totalCount = Integer.valueOf(item_quantity);

        et_height = (EditText) view.findViewById(R.id.et_height);
        et_kg = (EditText) view.findViewById(R.id.et_kg);

        View view_top = view.findViewById(R.id.view_top);
        view_top.setOnClickListener(this);

        final AbsListView.LayoutParams params = new AbsListView.LayoutParams(new WindowsUtils(this)
                .getScreenWidth(), new WindowsUtils(this).getScreenHeight());
        view.setLayoutParams(params);
        popupWindow = new PopupWindow(view, new WindowsUtils(this)
                .getScreenWidth(), new WindowsUtils(this).getScreenHeight());
        popupWindow.setBackgroundDrawable(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
        popupWindow.setOutsideTouchable(true);
        popupWindow.setFocusable(true);
        popupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);
        //在底部显示Popupwindow
        popupWindow.showAtLocation(tv_buy, Gravity.BOTTOM, 0, 0);

    }

    /**
     * 得到颜色   RadioGroup 的子控件
     */
    private void getColorRgChildView(List<DesignerDetailBuyColor> list, RadioGroup rg, int w) {
        for (int i = 0; i < list.size(); i++) {
            RadioButton rb = new RadioButton(this);
            RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(w, LinearLayout.LayoutParams.MATCH_PARENT);
            rb.setGravity(Gravity.CENTER);
            rb.setBackgroundResource(R.drawable.bg_color_rb);
            rb.setButtonDrawable(android.R.color.transparent);
            params.leftMargin = 30;
            rb.setLayoutParams(params);
            rb.setText(list.get(i).getItem_color());
            rg.addView(rb);
        }
    }

    /**
     * 得到颜色   RadioGroup 的子控件
     */
    private void getRgSizeChildView(List<DesignerDetailBuyItem> list, RadioGroup rg, int w) {
        for (int i = 0; i < list.size(); i++) {
            RadioButton rb = new RadioButton(this);
            RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(w, LinearLayout.LayoutParams.MATCH_PARENT);
            rb.setGravity(Gravity.CENTER);
            rb.setBackgroundResource(R.drawable.bg_color_rb);
            rb.setButtonDrawable(android.R.color.transparent);
            params.leftMargin = 30;
            rb.setLayoutParams(params);
            rb.setText(list.get(i).getItem_size());
            rg.addView(rb);
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1://颜色的RadioGroup
                    getColorRgChildView(corolList, rg_color, 100);

                    break;
                case 2://尺寸的RadioGroup
                    getRgSizeChildView(sizeList, rg_size, 80);
                    break;

            }
        }
    };

    /**
     * 解析购买界面的颜色
     */
    private void getBuyColor() {
        corolList.clear();
        Map<String, String> map = new HashMap<>();
        map.put("id", id);
        x.http().post(ResultParamsUtils.getIDParams(PathConstant.BUY_COLOR, map), new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                BaseDesignerDetailBuyColor base = JSONObject.parseObject(result, BaseDesignerDetailBuyColor.class);
                List<DesignerDetailBuyColor> list = base.getData().getList();
                corolList.addAll(list);
                handler.sendEmptyMessage(1);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                LogUtil.e(ex.toString());
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    /**
     * 解析购买界面尺寸界面
     */
    private void getBuySize() {
        sizeList.clear();
        Map<String, String> map = new HashMap<>();
        map.put("id", id);
        x.http().post(ResultParamsUtils.getIDParams(PathConstant.BUY_SIZE, map), new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                BaseDesignerDetailBuy base = JSONObject.parseObject(result, BaseDesignerDetailBuy.class);
                List<DesignerDetailBuyItem> list = base.getData().getList();
                sizeList.addAll(list);
                handler.sendEmptyMessage(2);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                LogUtil.e(ex.toString());
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    /**
     * 颜色，尺寸RadioGroup事件监听
     *
     * @param group
     * @param checkedId
     */

    private boolean isCheckedColor = false;
    private boolean isCheckedSize = false;
    private DbBuyDetail dbBuyDetail = new DbBuyDetail();

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        if (group == rg_color) {//选中颜色的RadioGroup
            isCheckedColor = true;
            for (int i = 0; i < group.getChildCount(); i++) {
                RadioButton childAt = (RadioButton) group.getChildAt(i);
                if (childAt.isChecked()) {
                    dbBuyDetail.setColor(corolList.get(i).getItem_color());
                }
            }
        }
        if (group == rg_size) {//选中颜色的RadioGroup
            isCheckedSize = true;
            for (int i = 0; i < group.getChildCount(); i++) {
                RadioButton childAt = (RadioButton) group.getChildAt(i);
                if (childAt.isChecked()) {
                    dbBuyDetail.setSize(sizeList.get(i).getItem_size());
                }
            }
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 取消注册EventBus
     *
     * @param str
     */


    @Subscriber(tag = "buy")
    public void getTotalString(String str) {
        if (!str.equals("")) {
            try {
                List<DbBuyDetail> all = BaseApp.getApp().getDb().findAll(DbBuyDetail.class);
                if (all.size() == 0) {
                    textNum.setVisibility(View.GONE);
                } else {
                    textNum.setVisibility(View.VISIBLE);
                    textNum.setText((all.size()) + "");
                }

            } catch (DbException e) {
                e.printStackTrace();
            }
        }
    }

}